/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package au.edu.swin.swinvehicle.corporateclient;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

/**
 *
 * @author Administrator
 */
public class NavigationCorporateClientController implements PhaseListener {

    public void afterPhase(PhaseEvent event) {
    }

    public void beforePhase(PhaseEvent event) {
        AuthenticationCorporateClientJSFManagedBean bean = (AuthenticationCorporateClientJSFManagedBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("AuthenticationCorporateClientJSFManagedBean");

        // Check if the user is logged in
        boolean isUserLoggedIn = false;
        if (bean.getCorporateClient() != null) {
            isUserLoggedIn = (bean.getCorporateClient().getId() == null) ? false : true;
        }

        FacesContext facesContext = event.getFacesContext();

        // If user is not logged in, redirect
        if (!(isUserLoggedIn)) {
            String viewIdString = facesContext.getViewRoot().getViewId();

            // Any user can see the login, addVehicleBooking page
            if (!viewIdString.contains("login")) {
                facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext, "", "login");
            }
        }
    }

    public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
    }
}
